package services

import (
	"fmt"
	"gin_study/app/helper"
	"gin_study/app/models"
	"gin_study/config"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func init() {
	dbConfig := config.Conf.Database
	dbSoureName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Database)
	database, err := gorm.Open(mysql.Open(dbSoureName), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	DB = database
}

func FetchUserLists() helper.Response {
	users := []models.User{}
	DB.Find(&users)
	return helper.SendResponse(users, 0, "success")
}

func FindOneUser(id string) helper.Response {
	user := models.User{}
	db := DB.Where("id", id).First(&user)
	if db.Row() == nil {
		return helper.SendResponse(struct{}{}, 0, "success")
	}
	return helper.SendResponse(user, 0, "success")
}

func ChangeUserName(id, name string) helper.Response {
	if len(id) < 1 || len(name) < 1 {
		return helper.SendResponse(struct{}{}, 1, "params error")
	}
	user := models.User{}
	db := DB.Where("id", id).First(&user)
	if db.Row() == nil {
		return helper.SendResponse(struct{}{}, 1, "no user")
	}
	db.Update("name", name)
	return helper.SendResponse(struct{}{}, 0, "success")
}
